﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AUV5.Common
{
    public class MailHelper
    {
        public static readonly string EMAIL_REGULAR_EXPRESSION = @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

        private static readonly string EMAIL_SMTP_HOST = "mail2.auv5.com";//119.225.26.256//"mail2.auv5.com";

        private static readonly int EMAIL_SMTP_PORT = 25;

        private static readonly string EMAIL_FROM = "business@wsitech.com";

        private static readonly string EMAIL_USERNAME = "business";

        private static readonly string EMAIL_PASSWORD = "passw0rd@wsitech.com";

        //private static readonly string EMAIL_LOGO_PATH = "http://www.woohr.com/client/Images/Logo.png";

        public MailHelper()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary> 
        /// 发送邮件 
        /// </summary> 
        /// <param name="to">收件人邮件地址</param> 
        /// <param name="from">发件人邮件地址</param> 
        /// <param name="subject">邮件主题</param> 
        /// <param name="body">邮件内容</param> 
        /// <param name="attachmentsPath">附件集合</param>
        /// <param name="username">登录smtp主机时用到的用户名,注意是邮件地址'@'以前的部分</param> 
        /// <param name="password">登录smtp主机时用到的用户密码</param> 
        /// <param name="smtpHost">发送邮件用到的smtp主机</param> 
        private void Send(System.Collections.ArrayList mailToList, string from, string subject, string body, string[] attachmentsPath, string userName, string password, string smtpHost)
        {
            try
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

                //发件人地址
                if (string.IsNullOrEmpty(from))
                {
                    from = EMAIL_FROM;
                }

                message.From = new System.Net.Mail.MailAddress(from, from.Split('@')[0], System.Text.Encoding.UTF8);

                //收件人地址的集合
                for (int i = 0; i < mailToList.Count; i++)
                {
                    if (mailToList[i] != null)
                    {
                        if (System.Text.RegularExpressions.Regex.IsMatch(mailToList[i].ToString(), EMAIL_REGULAR_EXPRESSION, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                        {
                            System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(mailToList[i].ToString());

                            message.To.Add(address);
                        }
                    }
                }

                //message.To.Add("wxyfgh@gmail.com");
                //message.To.Add("winfar@qq.com");

                //邮件主题行(标题)编码
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                //邮件主题行(标题)
                message.Subject = subject;
                //邮件正文是否为html格式
                message.IsBodyHtml = true;
                //邮件正文内容编码
                message.BodyEncoding = System.Text.Encoding.UTF8;
                //邮件正文内容
                message.Body = body;
                //邮件优先级
                message.Priority = System.Net.Mail.MailPriority.Normal;

                //给邮件体添加附件:在有附件的情况下添加附件
                try
                {
                    if (attachmentsPath != null && attachmentsPath.Length > 0)
                    {
                        System.Net.Mail.Attachment attachFile = null;
                        foreach (string path in attachmentsPath)
                        {
                            attachFile = new System.Net.Mail.Attachment(path);
                            message.Attachments.Add(attachFile);
                        }
                    }
                }
                catch (Exception err)
                {
                    throw new Exception("在添加附件时有错误:" + err);
                }

                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpHost, EMAIL_SMTP_PORT);
                smtp.UseDefaultCredentials = true;
                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtp.Credentials = new System.Net.NetworkCredential(userName, password);

                smtp.Send(message);

                //异步
                //string userState = "test message1";
                //smtp.SendAsync(message, userState);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="mailToList">收件人集合</param>
        /// <param name="subject">主题</param>
        /// <param name="body">内容</param>
        public void SendMail(string mailToStr, string subject, System.Text.StringBuilder body)
        {
            System.Collections.ArrayList mailToSingleList = new System.Collections.ArrayList(); 
            try
            {
                string[] mailToArray = null;

                if (mailToStr.Contains(","))
                {
                    mailToArray = mailToStr.Split(',');
                }
                else if (mailToStr.Contains(";"))
                {
                    mailToArray = mailToStr.Split(';');
                }
                else
                {
                    mailToArray = new string[] { mailToStr };
                }

                for (int i = 0; i < mailToArray.Length; i++)
                {
                    //mailToSingleList = new System.Collections.ArrayList();
                    mailToSingleList.Add(mailToArray[i]);
                    Send(mailToSingleList, EMAIL_FROM, subject, body.ToString(), null, EMAIL_USERNAME, EMAIL_PASSWORD, EMAIL_SMTP_HOST);//124.254.63.149
                }

            }
            catch (Exception)
            {
                Send(mailToSingleList, EMAIL_FROM, subject, body.ToString(), null, EMAIL_USERNAME, EMAIL_PASSWORD, "192.168.1.83");//使用IP访问邮件服务器（局域网内使用）
            }
        }

        /// <summary>
        /// 发送忘记密码邮件
        /// </summary>
        /// <param name="mailToList">收件人集合</param>
        /// <param name="subject">主题</param>
        /// <param name="body">内容</param>
        private void SendMailPassword(string mailToStr, string subject, System.Text.StringBuilder body)
        {
            try
            {
                System.Collections.ArrayList mailToSingleList = new System.Collections.ArrayList();

                mailToSingleList.Add(mailToStr);
                this.Send(mailToSingleList, EMAIL_FROM, subject, body.ToString(), null, EMAIL_USERNAME, EMAIL_PASSWORD, EMAIL_SMTP_HOST);//124.254.63.149;

            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
